# -*- coding: utf-8 -*-
from django.http import HttpResponse, Http404
from google.appengine.ext import db
from apps.pic.models import Pic
from apps.pic.forms import PicForm
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from google.appengine.api import images
from google.appengine.api.images import Image, Error, LargeImageError
import copy
from django.utils import simplejson as json

def getpic(request, type, size, aid):
    
    tPic = Pic.all().filter('aid = ', aid).filter('size = ', size).order('-date')
    
    if tPic.count():
        tPic = tPic.get()
        pic = tPic.pic
    else:
        pic = Pic.all().filter('aid = ', type).filter('size = ', size).get().pic
    

    return HttpResponse(pic, mimetype="image/JPEG")


def postpic(request):
    aid = request.POST.get("aid")

    if request.method == 'POST':
        nexturl = request.POST.get("nexturl")
        form = PicForm(request.POST, request.FILES)
        if request.FILES['pic'].size > ( 1 * 1023 * 1024 ) :
            return HttpResponse("图片不能超过 1MB ，后退重新传吧...")
        if form.is_valid():
            if Pic.all().filter('aid = ', aid).count() > 0 :
                for tPic in Pic.all().filter('aid = ', aid).fetch(4):
                    tPic.delete()  
            
            try:
                a = form.save()
                print request.FILES.items()
                pic = a.pic
                spic = images.resize(pic, 90, 120, images.JPEG)
                mpic = images.resize(pic, 160, 200, images.JPEG)
                
                tsPic = Pic(aid=a.aid, size="s", pic=db.Blob(spic))
                tmPic = Pic(aid=a.aid, size="m", pic=db.Blob(mpic))

                tsPic.put()
                tmPic.put()
            except Exception:
                return HttpResponse("图片格式不符 ，后退重新传吧...")# TOO LARGE
            return HttpResponseRedirect(nexturl) # OK
        return HttpResponse("没有上传图片啊， 后退重新传吧...")# no image

    raise Http404

def pic(request):
    tPiclist = Pic.all().filter('size = ', "l").order('-date')
    form = PicForm(initial={'aid': 'test'})
    return render_to_response('pic/pic.html', 
                            {'Piclist': tPiclist,
                            'form': form})  
    
def allpic(request, aid, type, size):
    tPic = Pic.all().filter('aid = ', aid).filter('size = ', size).order('-date')

    if tPic.count():
        tPic = tPic.get()
        pic = tPic.pic
    else:
        pic = Pic.all().filter('aid = ', type).filter('size = ', size).get().pic

    return HttpResponse(pic, mimetype="image/JPEG")

